import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 这个脚本主要用于执行部分基础sql，被Opengauss_Function_Guc_Connectionauthentication_Case0338调用
 * @Owner ：lwx1133724
 * @Create At： 2024/10/12
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Guc_connectionauthentication_Case0338 {
    public static void main(String[] args) {
        if (args.length < 4) {
            System.out.println("need para: host:ip,dbname,user,password");
            return;
        }

        Connection conn = null;
        Statement stmt = null;

        try {
            conn = DriverManager.getConnection(
                    "jdbc:postgresql://" + args[0] + "/" + args[1], args[2], args[3]);
            stmt = conn.createStatement();

            String[] sql_list = {
                "set idle_in_transaction_session_timeout to 30;",
                "set session_timeout to 0;",
                "show idle_in_transaction_session_timeout;",
                "show session_timeout;",
                "begin;",
                "select now();",
            };

            for (String sql : sql_list) {
                if (sql.trim().startsWith("select")) {
                    ResultSet resultSet = stmt.executeQuery(sql.trim());
                    while (resultSet.next()) {
                        System.out.println("Result: " + resultSet.getString(1));
                    }
                    resultSet.close();
                } else {
                    stmt.execute(sql.trim());
                }
            }

            try {
                stmt.execute("show now();");
            } catch (SQLException e) {
                System.out.println("Error executing 'show now();': " + e.getMessage());
            }

            Thread.sleep(31000);

            ResultSet resultSet = stmt.executeQuery("select now();");
            while (resultSet.next()) {
                System.out.println("Result: " + resultSet.getString(1));
            }
            resultSet.close();

            Thread.sleep(5000);
            stmt.execute("end;");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
